<template>
	<view class="container" @click="onUserInteraction">
		<!-- tabs部分，默认选中推荐（索引1） -->
		<u-tabs :current="activeTabIndex" :activeStyle="{ color: '#FFF' }" :inactiveStyle="{ color: '#f5f5f5' }"
			class="sticky" :list="list1" @click="onTabClick">
			<view slot="right" style="padding-left: 4px;" @tap="show = true">
				<u-icon name="list" size="21" bold color="#fff"></u-icon>
			</view>
		</u-tabs>
		<!-- 播放视频 -->
		<swiper :current="current" vertical @change="onSwiperChange" class="swiper-container" easing-function="linear"
			:circular="true">
			<swiper-item v-for="(video, index) in videos" :key="index" class="video-wrapper">
				<view style="height: 100%;width:100%">
					<!-- 去掉loop属性，以便触发ended事件 -->
					<video ref="videoPlayer" :id="'myVideo' + index" :src="video.src" :autoplay="current === index"
						class="video-player" @ended="onVideoEnded" controls playsinline webkit-playsinline @error="error"
						acceleration></video>
				</view>
			</swiper-item>
		</swiper>
		<!-- Loading spinner -->
		<view v-if="isLoading" class="loading-spinner">
			<view class="spinner"></view>
		</view>
		<u-popup :show="show" @close="close" @open="open" mode="center" bgColor="transparent">
			<view class="popup">
				<u-radio-group placement="column" v-model="radiovalue1">
					<u-radio :customStyle="{marginBottom: '8px',marginLeft: '8px'}" v-for="(item, index) in list1" :key="index"
						:label="item.name" :name="item.type">
					</u-radio>
				</u-radio-group>
				<!-- 上传视频 -->
				<view class="upload-video">
					<view class="upload-video-text" @tap="uploadVideo">
						<span v-if="isUploading">上传中</span>
						<span v-else>上传视频</span>
					</view>
				</view>
				<view v-if="isUploading" class="uploading-spinner">
					<view class="spinner"></view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// baseUrl: "http://192.168.1.9:3000",
				baseUrl: "",
				show: false,
				// Tab数据, 默认顺序不变, 默认选中‘推荐’（索引为1）
				list1: [{
						id: 0,
						name: '拿捏',
						type: 'pinchIt'
					},
					{
						id: 1,
						name: '挡不住',
						type: 'tikTok'
					},
					{
						id: 2,
						name: '推荐',
						type: 'recommended'
					},
					{
						id: 3,
						name: '长视频',
						type: 'lang'
					},
					{
						id: 4,
						name: '性感',
						type: 'sexy'
					},
					{
						id: 5,
						name: 'VR',
						type: 'VR'
					},
					{
						id: 6,
						name: '关注',
						type: 'like'
					},
					{
						id: 7,
						name: '我的',
						type: 'my'
					},
					{
						id: 8,
						name: '大尺度',
						type: 'cd'
					},

				],
				radiovalue1: "my",
				videos: [], // 视频列表
				current: 0, // 当前视频索引
				// 默认选中推荐类型
				currentType: 'tikTok',
				// u-tabs默认激活的tab索引
				activeTabIndex: 0,
				showPlayButton: true,
				playAttemptInterval: null,
				isUserInteracted: false,
				isLoading: false, // 控制loading spinner的显示
				isUploading: false, // 控制上传spinner的显示
				isScrolling: false, //
			};
		},
		async mounted() {
			// 加载初始视频数据
			await this.loadInitialVideos(this.activeTabIndex);

			// 监听鼠标固滚轮事件
			document.addEventListener('wheel', this.handleScrollevent);
		},
		beforeDestroy() {
			// 清除播放尝试定时器
			clearInterval(this.playAttemptInterval);
			// 移除鼠标滚轮事件监听
			document.removeEventListener('wheel', this.handleScrollevent);
		},
		methods: {
			async handleScrollevent(event) {
				if (this.isScrolling) {
					return; // 如果已经在滑动中，直接返回
				}
				this.isScrolling = true; // 设置标志位为 true，表示正在滑动

				if (event.deltaY > 0) {
					// 向下滚动
					this.scrollDown().finally(() => {
						this.isScrolling = false; // 操作完成后重置标志位
					});
				} else {
					// 向上滚动
					this.scrollUp().finally(() => {
						this.isScrolling = false; // 操作完成后重置标志位
					});
				}
			},


			async scrollDown() {
				// 暂停前一个视频的播放
				// const videoPlayerPrevious = this.$refs.videoPlayer[this.current];
				const videoPlayerPrevious = uni.createVideoContext('myVideo' + this.current);;
				if (videoPlayerPrevious) {
					videoPlayerPrevious.pause();
				}
				this.current = this.current + 1;

				// 如果切换到最后一个视频，则加载新视频
				if (this.current === this.videos.length - 1) {
					await this.loadNewVideo(this.activeTabIndex);
				}
				this.playCurrentVideo();
			},


			async scrollUp(time) {
				// 暂停前一个视频的播放
				// const videoPlayerPrevious = this.$refs.videoPlayer[this.current];
				const videoPlayerPrevious = uni.createVideoContext('myVideo' + this.current);;
				if (videoPlayerPrevious) {
					videoPlayerPrevious.pause();
				}
				if (this.current != 0) {
					this.current = this.current - 1;

					// 如果切换到最后一个视频，则加载新视频
					if (this.current === this.videos.length - 1) {
						await this.loadNewVideo(this.activeTabIndex);
					}
					this.playCurrentVideo();
				}
			},

			// tab点击事件，参数为选中的tab对象
			async onTabClick(tabItem) {
				// 暂停前一个视频的播放
				// const videoPlayerPrevious = this.$refs.videoPlayer[this.current];
				const videoPlayerPrevious = uni.createVideoContext('myVideo' + this.current);
				if (videoPlayerPrevious) {
					videoPlayerPrevious.pause();
				}
				this.isLoading = true; // 显示loading动画
				// 更换当前类型
				this.currentType = tabItem.type;
				// 更新激活的tab索引
				this.activeTabIndex = tabItem.id;
				// 重置视频数组和当前播放索引
				this.videos = [];
				this.current = 0;
				// 加载初始视频数据
				await this.loadInitialVideos(this.activeTabIndex);
				setTimeout(() => {
					this.isLoading = false; // 显示loading动画
				}, 500)
			},
			// 初始加载3个视频
			async loadInitialVideos(activeTabIndex) {
				for (let i = 0; i < 3; i++) {
					await this.loadNewVideo(activeTabIndex);
				}
			},
			// 请求新的视频数据，拼接type参数
			loadNewVideo(activeTabIndex) {
				return new Promise((resolve, reject) => {
					// 根据当前类型拼接请求地址
					let videoUrl = this.baseUrl + `/video?type=${this.currentType}`;
					if (activeTabIndex === 0) {
						videoUrl = "http://api.yujn.cn/api/zzxjj.php?type=video";
					}
					if (activeTabIndex === 8) {
						videoUrl = "https://api.magisk.icu/API/videos.php";
					}
					// 此处直接push URL地址，实际项目中可以使用uni.request获取数据后生成blob URL
					this.videos.push({
						src: videoUrl
					});
					resolve();
				});
			},
			// 切换swiper时调用
			async onSwiperChange(event) {
				const currentIndex = event.detail.current;
				// 暂停前一个视频的播放
				// const videoPlayerPrevious = this.$refs.videoPlayer[this.current];
				const videoPlayerPrevious = uni.createVideoContext('myVideo' + this.current);;
				if (videoPlayerPrevious) {
					videoPlayerPrevious.pause();
				}
				this.current = currentIndex;

				// 如果切换到最后一个视频，则加载新视频
				if (currentIndex === this.videos.length - 1) {
					await this.loadNewVideo(this.activeTabIndex);
				}
				this.playCurrentVideo();
			},
			// 播放当前视频
			playCurrentVideo() {
				this.$nextTick(() => {
					// 获取当前video播放器
					// const videoPlayer = this.$refs.videoPlayer[this.current];
					const videoPlayer = uni.createVideoContext('myVideo' + this.current);;
					if (videoPlayer && videoPlayer.play) {
						videoPlayer.play()
					}
				});
			},
			// 开启定时器，尝试播放视频
			startPlayAttemptInterval() {
				if (!this.playAttemptInterval) {
					this.playAttemptInterval = setInterval(() => {
						// const videoPlayer = this.$refs.videoPlayer[this.current];
						const videoPlayer = uni.createVideoContext('myVideo' + this.current);;
						if (videoPlayer && videoPlayer.play) {
							videoPlayer.play().then(() => {
								clearInterval(this.playAttemptInterval);
								this.playAttemptInterval = null;
							}).catch(() => {});
						}
					}, 500);
				}
			},
			// 视频播放完毕后的回调
			onVideoEnded() {
				// 自动播放下一个视频
				this.playNextVideo();
			},
			error() {
				uni.toast({
					title: '视频加载失败',
					icon: 'none'
				})
			},
			// 播放下一个视频
			playNextVideo() {
				// 切换到下一个视频
				this.current = (this.current + 1) % this.videos.length;
				this.playCurrentVideo();
			},
			// 用户交互时触发
			onUserInteraction() {
				this.showPlayButton = false;
				this.isUserInteracted = true;
				clearInterval(this.playAttemptInterval);
				this.playAttemptInterval = null;
				const videoPlayer = uni.createVideoContext('myVideo' + this.current);;
				// const videoPlayer = this.$refs.videoPlayer[this.current];
				if (videoPlayer) {
					videoPlayer.play()
				}
			},
			close() {
				this.show = false;
			},
			open() {
				this.show = true;
			},

			uploadVideo() {
				this.isUploading = true; // 显示上传动画

				uni.chooseVideo({
					count: 1,
					sourceType: ['album', 'camera'],
					success: (res) => {
						const tempFilePath = res.tempFilePath;
						uni.uploadFile({
							url: this.baseUrl + '/api/upload?dir=' + this.radiovalue1,
							filePath: tempFilePath,
							name: 'video',
							success: (uploadFileRes) => {
								if (uploadFileRes.statusCode == 200) {
									uni.showToast({
										title: '上传成功',
										icon: 'success'
									});
								} else {
									uni.showToast({
										title: '上传失败',
										icon: 'none'
									});
								}
								this.show = false; // 关闭弹窗
								this.isUploading = false; // 隐藏上传动画
							},
							fail: () => {
								uni.showToast({
									title: '上传失败',
									icon: 'none'
								});
								this.isUploading = false; // 隐藏上传动画
							}
						});
					},
					fail: () => {
						uni.showToast({
							title: '选择视频失败',
							icon: 'none'
						});
						this.isUploading = false; // 隐藏上传动画
					}
				});
			},
		}
	}
</script>

<style lang="scss">
	.container {
		width: 100vw;
		height: 100vh;
		background-color: black;
		overflow: hidden;
		position: relative;

		::v-deep .sticky {
			width: 100vw;
			box-sizing: border-box;
			padding: 0 20rpx;
			position: absolute;
			top: 20px;
			left: 50%;
			transform: translate(-50%);
			z-index: 1;
		}
	}

	.swiper-container {
		width: 100vw;
		height: 100vh;
	}

	.video-wrapper {
		position: relative;
		width: 100vw;
		height: 100vh;
	}

	.video-player {
		width: 100vw;
		height: 100vh;
	}

	.play-button {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		background-color: rgba(0, 0, 0, 0.7);
		color: white;
		padding: 10px 20px;
		border-radius: 5px;
		cursor: pointer;
	}

	.loading-spinner {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		z-index: 2;
	}

	.uploading-spinner {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		z-index: 3;
	}

	.spinner {
		border: 4px solid rgba(255, 255, 255, 0.3);
		border-top: 4px solid #fff;
		border-radius: 50%;
		width: 40px;
		height: 40px;
		animation: spin 1s linear infinite;
	}

	.popup {
		width: 80vw;
		box-sizing: border-box;
		padding: 60rpx 40rpx;
		background-color: #fff;
		border-radius: 40rpx;
		display: flex;
		flex-direction: column;
		justify-content: center;

		.upload-video {

			width: 100%;
			height: 70rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			background-color: #fff;
			border-radius: 10rpx;
			margin-top: 60rpx;

			.upload-video-text {
				width: 200rpx;
				height: 60rpx;
				line-height: 60rpx;
				text-align: center;
				background-color: #007aff;
				color: #fff;
				border-radius: 30rpx;
				font-size: 28rpx;

			}

			.upload-video-fff {
				margin-left: 50rpx;
				width: 200rpx;
				height: 60rpx;
				line-height: 60rpx;
				text-align: center;
				color: #fff;
				background-color: seagreen;
				border-radius: 30rpx;
				font-size: 28rpx;
				border: 1rpx solid #333;
			}
		}
	}

	@keyframes spin {
		0% {
			transform: rotate(0deg);
		}

		100% {
			transform: rotate(360deg);
		}
	}
</style>